/**
 * 知乎平台处理器
 * 简单的格式转换和基本校验
 */

import { createLogger, ILogger } from '../../utils/logger';
import { 
  PublishPlatform, 
  IContent, 
  IValidationResult, 
  IPublishOptions, 
  IPublishResult, 
  IPlatformHandler 
} from './interfaces';

export class ZhihuPlatform implements IPlatformHandler {
  public readonly platform = PublishPlatform.ZHIHU;
  private readonly logger: ILogger;

  constructor(logger?: ILogger) {
    this.logger = logger || createLogger('ZhihuPlatform');
  }

  /**
   * 格式化内容 - 转换为知乎支持的Markdown格式
   */
  async formatContent(content: IContent): Promise<IContent> {
    const formatted = { ...content };

    try {
      // 1. 转换为Markdown格式
      if (content.format === 'html') {
        formatted.content = this.htmlToMarkdown(content.content);
        formatted.format = 'markdown';
      }

      // 2. 处理标题长度限制
      if (formatted.title.length > 100) {
        formatted.title = formatted.title.substring(0, 97) + '...';
        this.logger.warn('Title truncated to 100 characters for Zhihu');
      }

      // 3. 处理标签数量限制
      if (formatted.tags && formatted.tags.length > 5) {
        formatted.tags = formatted.tags.slice(0, 5);
        this.logger.warn('Tags limited to 5 for Zhihu');
      }

      return formatted;
    } catch (error) {
      this.logger.error('Failed to format content for Zhihu', error as Error);
      return content;
    }
  }

  /**
   * 验证内容
   */
  validateContent(content: IContent): IValidationResult {
    const errors: string[] = [];
    const warnings: string[] = [];

    // 基本验证
    if (!content.title || content.title.trim().length === 0) {
      errors.push('标题不能为空');
    }

    if (!content.content || content.content.trim().length === 0) {
      errors.push('内容不能为空');
    }

    // 知乎特定验证
    if (content.title.length > 100) {
      warnings.push('标题长度超过100字符，将被截断');
    }

    if (content.tags && content.tags.length > 5) {
      warnings.push('标签数量超过5个，将被截断');
    }

    const textLength = content.content.replace(/<[^>]*>/g, '').length;
    if (textLength > 100000) {
      errors.push('内容长度超过知乎限制（100,000字符）');
    }

    if (textLength < 50) {
      warnings.push('内容长度较短，建议至少50字符');
    }

    return {
      valid: errors.length === 0,
      errors,
      warnings
    };
  }

  /**
   * 发布内容
   */
  async publish(content: IContent, options?: IPublishOptions): Promise<IPublishResult> {
    try {
      this.logger.info('Publishing to Zhihu...');

      // 格式化内容
      const formattedContent = await this.formatContent(content);

      // 验证内容
      const validation = this.validateContent(formattedContent);
      if (!validation.valid) {
        return {
          success: false,
          error: `Validation failed: ${validation.errors.join(', ')}`
        };
      }

      // TODO: 实际的发布逻辑
      // 这里应该调用知乎的API或使用自动化工具发布
      
      this.logger.info('Content published to Zhihu successfully');
      
      return {
        success: true,
        url: 'https://zhuanlan.zhihu.com/p/example',
        articleId: 'example-id',
        metadata: {
          platform: 'zhihu',
          publishTime: new Date(),
          isDraft: options?.isDraft || false
        }
      };

    } catch (error) {
      this.logger.error('Failed to publish to Zhihu', error as Error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * HTML转Markdown - 简单转换
   */
  private htmlToMarkdown(html: string): string {
    return html
      // 标题
      .replace(/<h1[^>]*>(.*?)<\/h1>/gi, '# $1\n\n')
      .replace(/<h2[^>]*>(.*?)<\/h2>/gi, '## $1\n\n')
      .replace(/<h3[^>]*>(.*?)<\/h3>/gi, '### $1\n\n')
      .replace(/<h4[^>]*>(.*?)<\/h4>/gi, '#### $1\n\n')
      .replace(/<h5[^>]*>(.*?)<\/h5>/gi, '##### $1\n\n')
      .replace(/<h6[^>]*>(.*?)<\/h6>/gi, '###### $1\n\n')
      
      // 段落
      .replace(/<p[^>]*>(.*?)<\/p>/gi, '$1\n\n')
      
      // 格式化
      .replace(/<strong[^>]*>(.*?)<\/strong>/gi, '**$1**')
      .replace(/<b[^>]*>(.*?)<\/b>/gi, '**$1**')
      .replace(/<em[^>]*>(.*?)<\/em>/gi, '*$1*')
      .replace(/<i[^>]*>(.*?)<\/i>/gi, '*$1*')
      .replace(/<code[^>]*>(.*?)<\/code>/gi, '`$1`')
      
      // 链接和图片
      .replace(/<a[^>]*href="([^"]*)"[^>]*>(.*?)<\/a>/gi, '[$2]($1)')
      .replace(/<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"[^>]*>/gi, '![$2]($1)')
      .replace(/<img[^>]*src="([^"]*)"[^>]*>/gi, '![]($1)')
      
      // 列表
      .replace(/<ul[^>]*>([\s\S]*?)<\/ul>/gim, '$1\n')
      .replace(/<ol[^>]*>([\s\S]*?)<\/ol>/gim, '$1\n')
      .replace(/<li[^>]*>(.*?)<\/li>/gi, '- $1\n')

      // 引用和代码块
      .replace(/<blockquote[^>]*>([\s\S]*?)<\/blockquote>/gim, '> $1\n\n')
      .replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gim, '```\n$1\n```\n\n')
      
      // 换行
      .replace(/<br\s*\/?>/gi, '\n')
      .replace(/<hr\s*\/?>/gi, '\n---\n\n')
      
      // 清理剩余HTML标签
      .replace(/<[^>]*>/g, '')
      
      // 清理多余空行
      .replace(/\n{3,}/g, '\n\n')
      .trim();
  }
}
